package cn.org.qary.controller.rking.front;

import cn.org.qary.entity.User;
import cn.org.qary.service.trait.rking.UserService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
public class FileController {
    @Autowired
    UserService userService;
//    @RequestMapping("download")
//    public String xz(String filename, HttpServletRequest request, HttpServletResponse response, Model m) throws Exception {
//        String url = request.getSession().getServletContext().getRealPath("js");
//        System.out.println("下载路径"+url);
//        File file = new File(url,filename);
//        if(file.exists()){
//            //表示响应类型为二进制文件
//            response.setContentType("application/octet-stream");
//            //下载文件名转码
//            filename = new String(filename.getBytes(),"iso-8859-1");
//            //attachment 弹窗下载 inline 直接打开
//            response.setHeader("content-disposition","attachment;filename="+filename);
//            ServletOutputStream os = response.getOutputStream();
//            os.write(FileUtils.readFileToByteArray(file));
//            os.close();
//            return null;
//        }
//        m.addAttribute("msg",filename+"该文件不存在");
//        return "emp";
//    }


    @RequestMapping("fileupload")
    public String sc(MultipartFile file, HttpSession session) throws IOException {
        User user = (User) session.getAttribute("user");
        String filename = user.getUsername()+"_qqAvatar.jpg";
        //文件上传位置
        String path = session.getServletContext().getRealPath("file");
        File targetFile = new File(path,filename);
        file.transferTo(targetFile);

        user.setImage("/file/"+filename);
        userService.update(user);
        return "myinfo";
    }
}
